import re
import base64
from django.conf import settings
import requests
# 返回api数据
def ReturnData(code = 200,  msg = 'success',data=None):
    return {
        "code": code,
        "msg": msg,
        "data": data
    }

# 获取第一个错误信息
def get_first_error(form):
    first_error = next(iter(form.errors.items()))
    field_name, error_list = first_error
    error_msg = f"{error_list[0]}"
    return error_msg

# 判断url是否是正确的http或https
def is_valid_url(url):
    return re.match(r'^https?://', url) is not None


# 获取请求协议 + 域名
def get_request_protocol_and_domain(request):
    protocol = request.META.get('HTTP_X_FORWARDED_PROTO', 'http')
    domain = request.META.get('HTTP_HOST')
    return f"{protocol}://{domain}"


# base64加密文本
def base64_encode(text):
    
    return base64.b64encode(text.encode('utf-8')).decode('utf-8')



# 返回登录链接
def get_login_url(request):
    return settings.BLACKWIDOW_DOMAIN + f"/web/pc/v1/login/?redirect={base64_encode(f"{get_request_protocol_and_domain(request)}/api/system/receive_notification/")}"

# 通知对方的服务器
def send_platform_info_msg(platform_info_msg_url, data):
    try:
        response = requests.post(
            url=platform_info_msg_url,
            json=data, 
            headers={'Content-Type': 'application/x-www-form-urlencoded'},
        )
        print(f"通知结果: {response.text}")
        return response.status_code == 200
    except requests.Timeout:
        return False
    except Exception:
        return False